﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Configuration;

namespace SocialFront.Providers
{
    public abstract class SocialFrontProviderManager<T> where T : SocialFrontProviderBase
    {
        private static T defaultProvider;
        private static SocialFrontProviderCollection<T> providers;

        static SocialFrontProviderManager()
        {
            Initialize();
        }

        private static void Initialize()
        {

            SocialFrontProviderConfiguration configuration =
                (SocialFrontProviderConfiguration)
                ConfigurationManager.GetSection(GetSectionName<T>());

            if (configuration == null)
                throw new ConfigurationErrorsException
                    (GetSectionName<T>() + " configuration section is not set correctly.");

            providers = new SocialFrontProviderCollection<T>();

            ProvidersHelper.InstantiateProviders(configuration.Providers, providers, typeof(T));

            providers.SetReadOnly();

            defaultProvider = providers[configuration.Default];

            if (defaultProvider == null)
                throw new Exception("defaultProvider");
        }

        #region Utilities

        /// <summary>  
        /// Returns the appropriate provider configuration section name  
        /// </summary>  
        public static string GetSectionName<T>() where T : SocialFrontProviderBase
        {
            return (typeof(T).GetCustomAttributes(typeof(SectionNameAttribute), true)[0] as SectionNameAttribute).SectionName;
        }

        #endregion

        #region Properties

        public static T Provider
        {
            get
            {
                return defaultProvider;
            }
        }

        public static SocialFrontProviderCollection<T> Providers
        {
            get
            {
                return providers;
            }
        }

        #endregion
    }
}
